using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace AutoUpdater
{
    /// <summary>
    /// INI文件操作类
    /// </summary>
    public class IniFile
    {
        private readonly string _path;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="path">INI文件路径</param>
        public IniFile(string path)
        {
            _path = path;
        }

        /// <summary>
        /// 写入INI文件
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public void Write(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value ?? "", _path);
        }

        /// <summary>
        /// 读取INI文件（使用Unicode编码，支持中文）
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public string Read(string section, string key)
        {
            // 使用StringBuilder接收结果，指定足够大的容量（避免截断）
            var sb = new StringBuilder(1024);

            // 调用Unicode版本API，确保中文正确读取
            GetPrivateProfileString(section, key, "", sb, sb.Capacity, _path);

            // 清理可能的空字符或乱码
            return CleanUpText(sb.ToString());
        }

        /// <summary>
        /// 清理文本中的无效字符
        /// </summary>
        private string CleanUpText(string text)
        {
            if (string.IsNullOrEmpty(text))
                return string.Empty;

            // 移除字符串前后的空白和控制字符
            return text.Trim().Replace("\0", "");
        }

        /// <summary>
        /// 删除节
        /// </summary>
        /// <param name="section">节</param>
        public void DeleteSection(string section)
        {
            Write(section, null, null);
        }

        /// <summary>
        /// 删除键
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="key">键</param>
        public void DeleteKey(string section, string key)
        {
            Write(section, key, null);
        }

        /// <summary>
        /// 检查INI文件是否存在
        /// </summary>
        /// <returns>是否存在</returns>
        public bool Exists()
        {
            return File.Exists(_path);
        }
    }
}
    